package com.example.listener;

import com.example.config.TransactionMessageHandler;
import lombok.AllArgsConstructor;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;

import static org.apache.rocketmq.spring.core.RocketMQLocalTransactionState.*;

import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.messaging.Message;

import java.util.List;
import java.util.Optional;

/**
 * @author zxs
 * @since 2021/5/27
 */
@AllArgsConstructor
//@RocketMQTransactionListener
public class DefaultTransactionListener implements RocketMQLocalTransactionListener {

    private final List<TransactionMessageHandler> handlers;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {

        RocketMQLocalTransactionState state = UNKNOWN;
        try {
            //全局事务id
            String transactionId = (String) msg.getHeaders().get(RocketMQHeaders.TRANSACTION_ID);
            //执行本地事务
            Optional<TransactionMessageHandler> handler = handlers.stream().filter(transactionMessageHandler -> transactionMessageHandler.support(msg)).findFirst();
            if (handler.isPresent()) {
                boolean success = handler.get().handleMessage(transactionId, msg.getPayload());
                if (success) {
                    //TODO 设置事务状态为 COMMIT
                    state = COMMIT;
                } else {
                    //TODO 设置事务状态为 ROLLBACK
                    state = ROLLBACK;
                }
            }
        } catch (Exception e) {
            //TODO 设置事务状态为 ROLLBACK
            state = ROLLBACK;
            e.printStackTrace();
        }
        return state;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        String transactionId = (String) msg.getHeaders().get(RocketMQHeaders.TRANSACTION_ID);
        //检查事务状态
        String state = "COMMIT";
        //检查本地事务状态
        return RocketMQLocalTransactionState.valueOf(state);
    }


}
